package com.chookss.home.running;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.entity.RunningActivityEntity;
import com.chookss.home.logContacts.ContactsLogChoiceActivity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BasisTimesUtils;
import com.chookss.view.DrawableTextView;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//新建活动列表
public class RunningAddActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.edTimeLengthInit)
    TextView edTimeLengthInit;
    @BindView(R.id.edTitle)
    EditText edTitle;
    @BindView(R.id.edDescribe)
    EditText edDescribe;
    @BindView(R.id.ivBg)
    ImageView ivBg;
    @BindView(R.id.llPic)
    LinearLayout llPic;
    @BindView(R.id.llMore)
    LinearLayout llMore;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edTimeLength)
    EditText edTimeLength;
    @BindView(R.id.tvStartTime)
    DrawableTextView tvStartTime;
    @BindView(R.id.tvEndTime)
    DrawableTextView tvEndTime;
    @BindView(R.id.tvChoicePic)
    DrawableTextView tvChoicePic;
    @BindView(R.id.rlSure)
    RelativeLayout rlSure;
    private MyContactEntityAdapter adapter;
    private List<ContactEntity> contactAllList = new ArrayList<>(); //用来存放所有数据
    private List<ContactEntity> contactLittleList = new ArrayList<>(); //人数不够《=15
    private String imgUrl = "";
    private static int SOURSE = 10;//选员工所用标识
    private boolean isEdit = false;//是否要编辑
    private String adminCode = "";
    private String activityCode = "", id = "";
    private boolean isDetail = false;//是否显示活动详情

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_running_add);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        activityCode = getIntent().getStringExtra("activityCode");
        isDetail = getIntent().getBooleanExtra("isDetail", false);
        id = getIntent().getStringExtra("id");
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 5);
        recyclerView.setLayoutManager(gridLayoutManager1);
        adapter = new MyContactEntityAdapter(R.layout.item_log_group_manager, this, contactLittleList);
        recyclerView.setAdapter(adapter);
        recyclerView.getItemAnimator().setAddDuration(0);
        recyclerView.getItemAnimator().setChangeDuration(0);
        recyclerView.getItemAnimator().setMoveDuration(0);
        recyclerView.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        adminCode = new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
        if (isDetail) {
            commonTitleTxt.setText("活动详情");
            tvChoicePic.setVisibility(View.GONE);
            edTimeLengthInit.setVisibility(View.GONE);
            edTimeLength.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
            rlSure.setVisibility(View.GONE);
            edTitle.setFocusable(false);
            edTitle.setFocusableInTouchMode(false);
            edTimeLength.setFocusable(false);
            edTimeLength.setFocusableInTouchMode(false);
            edDescribe.setFocusable(false);
            edDescribe.setFocusableInTouchMode(false);
            tvStartTime.setCompoundDrawables(null, null, null, null);
            tvEndTime.setCompoundDrawables(null, null, null, null);
            LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) edTimeLength.getLayoutParams();
            params.setMargins(0,0,Utils.dip2px(this,12),0);
            edTimeLength.setLayoutParams(params);
            getData();
        } else {
            edTimeLength.setInputType(InputType.TYPE_CLASS_NUMBER);
            edTimeLength.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (!Utils.isNull(s.toString())) {
                        if (Utils.changeNumber(s.toString()) < 1) {
                            edTimeLength.setText("1");
                            MyToast.show("有效同步时间最少为1天");
                        } else if (Utils.changeNumber(s.toString()) > 30) {
                            edTimeLength.setText("30");
                            MyToast.show("有效同步时间最多为30天");
                        }
                    }
                }
            });
            if (Utils.isNull(activityCode)) {
                commonTitleTxt.setText("创建活动");
                addBaseData();
            } else {
                commonTitleTxt.setText("修改活动");
                isEdit=true;
                getData();
            }
            edDescribe.setMaxHeight(Utils.getScreenHeight(this)*2/3);
            edDescribe.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    if ((view.getId() == R.id.edDescribe && canVerticalScroll(edDescribe))) {
                        view.getParent().requestDisallowInterceptTouchEvent(true);
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            view.getParent().requestDisallowInterceptTouchEvent(false);
                        }
                    }
                    return false;
                }
            });
        }
    }

    /**
     * EditText竖直方向是否可以滚动
     * @param editText 需要判断的EditText
     * @return true：可以滚动  false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }
    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("activityCode", activityCode);
        showLoading();
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<RunningActivityEntity>>() {
        }.getType(), null, Urls.selectMoveInfoDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<RunningActivityEntity>() {
            @Override
            public void onSuccess(RunningActivityEntity data) {
                dismissLoading();
                edTitle.setText(data.getActivityName());
                edDescribe.setText(data.getRemark());
                if (isDetail) {
                    edTimeLength.setText(Utils.changeNumber(data.getSyncDayNum()) + "天");
                }else{
                    edTimeLength.setText(Utils.changeNumber(data.getSyncDayNum()) + "");
                }

                if (!Utils.isNull(data.getStartTime())) {
                    if (data.getStartTime().length() >= 10) {
                        tvStartTime.setText(data.getStartTime().substring(0, 10));
                    }
                }
                if (!Utils.isNull(data.getEndTime())) {
                    if (data.getEndTime().length() >= 10) {
                        tvEndTime.setText(data.getEndTime().substring(0, 10));
                    }
                }
                llPic.setVisibility(View.VISIBLE);
                imgUrl = data.getImageUrl();
                GlideUtils.loadCustomRound(RunningAddActivity.this, imgUrl, ivBg, 8);
                List<RunningActivityEntity.ContactEntity> list = data.getEmps();
                for (int i = 0; i < list.size(); i++) {
                    ContactEntity contactEntity = new ContactEntity();
                    contactEntity.setType("1");
                    contactEntity.setEmployeeCode(list.get(i).getEmployeeCode());
                    contactEntity.setEmployeeName(list.get(i).getEmployeeName());
                    contactEntity.setHeadPhotoThumbUrl(list.get(i).getHeadPhotoThumbUrl());
                    if (!contactEntity.getEmployeeCode().equals(adminCode)) {
                        contactAllList.add(contactEntity);
                    }
                }
                setServerData();
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void addBaseData() {
        ContactEntity contactEntity = new ContactEntity();
        contactEntity.setType("1");
        contactEntity.setHeadPhotoThumbUrl(new ShareUtils().getString(this, StaticClass.USER_AVATAR_URL, ""));
        contactEntity.setEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        contactEntity.setEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        contactEntity.setPost(new ShareUtils().getString(this, StaticClass.POST, ""));
        if (contactAllList.size() == 0) {
            //第一次
            contactLittleList.add(contactEntity);
            contactAllList.add(contactEntity);
        } else {
            contactLittleList.add(0, contactEntity);
            contactAllList.add(0, contactEntity);
        }
        ContactEntity contactEntity2 = new ContactEntity();
        contactEntity2.setType("2");
        contactEntity2.setEmployeeName("2");
        contactEntity2.setEmployeeCode("2");
        if (!isDetail) {
            contactLittleList.add(contactEntity2);
        }
//        ContactEntity contactEntity3 = new ContactEntity();
//        contactEntity3.setType("3");
//        contactEntity3.setEmployeeName("3");
//        contactEntity3.setEmployeeCode("3");
//        contactLittleList.add(contactEntity3);
    }

    private void uploadData() {
        //把选择的部门里面的人全部查出来
        Map<String, Object> map = new HashMap<>();
        map.put("activityName", edTitle.getText().toString());
        map.put("imageUrl", imgUrl);
        map.put("startTime", tvStartTime.getText().toString());
        map.put("endTime", tvEndTime.getText().toString());
        map.put("syncDayNum", edTimeLength.getText().toString());
        map.put("remark", edDescribe.getText().toString());
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < contactAllList.size(); i++) {
            Map<String, String> maps = new HashMap<>();
            maps.put("employeeCode", contactAllList.get(i).getEmployeeCode());
            if (adminCode.equals(contactAllList.get(i).getEmployeeCode())) {
                maps.put("adminCd", "1");
            } else {
                maps.put("adminCd", "0");
            }
            list.add(maps);
        }
        map.put("emps", XJson.listToJsArrays(list));
        String url = "";
        if (Utils.isNull(activityCode)) {
            url = Urls.insertMoveInfo;
        } else {
            map.put("activityCode", activityCode);
            map.put("id", id);
            url = Urls.updateMoveInfo;
        }
        MyHttpRequest.postRequestJson(url, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        if (Utils.isNull(activityCode)) {
                            MyToast.show("活动创建成功");
                        } else {
                            MyToast.show("活动修改成功");
                        }
                        EventBus.getDefault().post(new MyEvent("RunningAddActivity_Publish"));
                        finish();
                    } else {

                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }

    private void uploadPic() {
        showLoading();
        MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "4", new File(imgUrl), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                JSONObject result = null;
                JSONObject data = null;
                try {
                    result = new JSONObject(response.body().toString());
                    if (result.getString("code").equals("200")) {
                        data = result.getJSONObject("data");
                        imgUrl = data.getString("originalUrl");
                        uploadData();
                    } else {
                        dismissLoading();
                        if (result.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                        } else {
                            MyToast.show("封面上传失败，请稍后重试");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("封面上传失败，请稍后重试");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                MyToast.show("图片上传失败，请稍后重试");
            }
        });

    }

    class MyContactEntityAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {
        private Context context;

        public MyContactEntityAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<ContactEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity item) {

            RelativeLayout rlInit = helper.getView(R.id.rlInit);
            RelativeLayout rlRl = helper.getView(R.id.rlRl);
            LinearLayout llType = helper.getView(R.id.llType);
            TextView tvName = helper.getView(R.id.tvName);
            ImageView ivRunning = helper.getView(R.id.ivRunning);
            ImageView ivHead = helper.getView(R.id.ivHead);
            ImageView ivType = helper.getView(R.id.ivType);
            llType.setVisibility(View.GONE);
            rlInit.setVisibility(View.GONE);
            if ("2".equals(item.getEmployeeCode())) {
                //+
                ivRunning.setVisibility(View.VISIBLE);
                ivRunning.setBackgroundResource(R.drawable.add_icon);
                rlRl.setVisibility(View.GONE);
                tvName.setVisibility(View.INVISIBLE);
                ivType.setVisibility(View.GONE);
            } else if ("3".equals(item.getEmployeeCode())) {
                //-
                ivRunning.setVisibility(View.VISIBLE);
                ivRunning.setBackgroundResource(R.drawable.jian_icon);
                rlRl.setVisibility(View.GONE);
                tvName.setVisibility(View.INVISIBLE);
                ivType.setVisibility(View.GONE);
            } else {
                //普通人
                ivRunning.setVisibility(View.GONE);
                rlRl.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(RunningAddActivity.this, item.getHeadPhotoThumbUrl(), ivHead, R.drawable.default_user_head, 8);
                tvName.setText(item.getEmployeeName());
                tvName.setVisibility(View.VISIBLE);
                if (isEdit) {
                    if (helper.getItemPosition() == 0) {
                        ivType.setVisibility(View.GONE);
                    } else {
                        ivType.setVisibility(View.VISIBLE);
                    }
                } else {
                    ivType.setVisibility(View.GONE);
                }
            }
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.isNull(item.getEmployeeCode())) {
                        return;
                    }
                    Intent intent = new Intent(RunningAddActivity.this, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", item.getEmployeeCode());
                    startActivity(intent);
                }
            });
            ivType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    contactLittleList.remove(helper.getItemPosition());
                    contactAllList.remove(helper.getItemPosition());
                    adapter.notifyItemRemoved(helper.getItemPosition());
                    adapter.notifyItemRangeChanged(helper.getItemPosition(), contactLittleList.size() - helper.getItemPosition());
                }
            });
            ivRunning.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.getType().equals("2")) {
//                    //默认0是编辑 1创建分组2预览分组
                        MyApp.contactEntityLogList.clear();
                        Intent intent = new Intent(RunningAddActivity.this, ContactsLogChoiceActivity.class);
                        intent.putExtra("source", SOURSE + "");
                        intent.putExtra("hrName", "已选择活动成员：");
                        startActivity(intent);
                        if (!isEdit) {
                            //之前是编辑状态 改成默认正常状态
                            isEdit = true;
                            adapter.notifyDataSetChanged();
                        }
                    } else {
                        isEdit = true;
                        adapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    private void requestSTORAGECamer() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {

                            PictureSelector.create(RunningAddActivity.this)
                                    .openGallery(SelectMimeType.ofImage())
                                    .isDisplayCamera(true)//是否显示相机入口
                                    .setMaxSelectNum(1)
                                    .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                    .isPreviewImage(true)//是否支持预览图片
                                    .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                    .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                    .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                    .forResult(PictureConfig.CHOOSE_REQUEST);
                        } else {
                            PermissionUtils.errorPermission(RunningAddActivity.this, granted, all);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(RunningAddActivity.this, denied, quick);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("ChoiceContacts_Ok_" + SOURSE)) {
                if (MyApp.contactEntityLogList.size() > 0) {
                    contactAllList.clear();
                    List<String> orgCodeList = new ArrayList<>();
                    List<String> employeeCodeList = new ArrayList<>();
                    for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                        ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                        if (!contactEntity.isHalfSelect()) {
                            if (contactEntity.getType().equals("0")) {
                                orgCodeList.add(contactEntity.getEmployeeCode());
                            } else {
                                employeeCodeList.add(contactEntity.getEmployeeCode());
                            }
                        }
                    }
                    if (orgCodeList.size() > 0) {
                        getServerData(orgCodeList, employeeCodeList);
                    } else {
                        //没有组织，
                        List<ContactEntity> acceptList = new ArrayList<>();
                        for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                            ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                            contactEntity.setType("1");
                            if (!contactEntity.isHalfSelect() && !contactEntity.getEmployeeCode().equals(adminCode)) {
                                acceptList.add(contactEntity);
                            }
                        }
                        contactAllList.addAll(acceptList);
                        setServerData();
                    }

                }
            }
        }
    }

    private void getServerData(List<String> orgCodeList, List<String> employeeCodeList) {
        //把选择的部门里面的人全部查出来
        Map<String, Object> map = new HashMap<>();
        map.put("orgCode", JSON.toJSONString(orgCodeList));
        map.put("employeeCode", JSON.toJSONString(employeeCodeList));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.getSelectedEmployee, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        List<ContactEntity> serverList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                            ContactEntity contactEntity = new ContactEntity();
                            contactEntity.setEmployeeName(jsonObject2.getString("employeeName"));
                            contactEntity.setEmployeeCode(jsonObject2.getString("employeeCode"));
                            contactEntity.setHeadPhotoThumbUrl(jsonObject2.getString("headPhotoThumbUrl"));
                            contactEntity.setType("1");
                            contactEntity.setEmpNum("0");
                            contactEntity.setReviewerFlag("0");
                            contactEntity.setHalfSelect(false);
                            contactEntity.setSelect(false);
                            if (!jsonObject2.getString("employeeCode").equals(adminCode)) {
                                serverList.add(contactEntity);
                            }
                        }
                        contactAllList.addAll(serverList);
                        setServerData();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }

    private void setServerData() {
        if (recyclerView == null) {
            return;
        }
        contactLittleList.clear();
        if(isDetail){
            if (contactAllList.size() > (15)) {
                contactLittleList.addAll(contactAllList.subList(0, 14));
                llMore.setVisibility(View.VISIBLE);
            } else {
                contactLittleList.addAll(contactAllList);
                llMore.setVisibility(View.GONE);
            }
        }else{
            if (contactAllList.size() > (14 )) {
                contactLittleList.addAll(contactAllList.subList(0, 13 ));
                llMore.setVisibility(View.VISIBLE);
            } else {
                contactLittleList.addAll(contactAllList);
                llMore.setVisibility(View.GONE);
            }
        }

        addBaseData();
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                //去除+号
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    imgUrl = url;
                }
                llPic.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(RunningAddActivity.this, imgUrl, ivBg, 8);
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.llMore, R.id.llChoicePic, R.id.tvSure, R.id.tvStartTime, R.id.tvEndTime})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.llChoicePic:
                if (!isDetail) {
                    requestSTORAGECamer();
                }
                break;
            case R.id.llMore:
                if (isDetail) {
                    contactLittleList.addAll(15, contactAllList.subList(15, contactAllList.size()));
                    adapter.notifyItemRangeChanged(15, contactAllList.size() - 15 );
                } else {
                    contactLittleList.addAll(14, contactAllList.subList(14, contactAllList.size()));
                    adapter.notifyItemRangeChanged(14, contactAllList.size() - 14 + 1);
                }
                llMore.setVisibility(View.GONE);
                break;
            case R.id.tvStartTime:
                if (!isDetail) {
                    showDatePickStartDialog();
                }
                break;
            case R.id.tvEndTime:
                if (!isDetail) {
                    showDatePickEndDialog();
                }
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (edTitle == null) {
                    return;
                }
                if (Utils.isNull(edTitle.getText().toString())) {
                    MyToast.show("请输入标题");
                    return;
                }
                if (Utils.isNull(tvStartTime.getText().toString())) {
                    MyToast.show("请选择活动开始时间");
                    return;
                }
                if (Utils.isNull(tvEndTime.getText().toString())) {
                    MyToast.show("请选择活动结束时间");
                    return;
                }
                if (Utils.isNull(edDescribe.getText().toString())) {
                    MyToast.show("请输入活动描述");
                    return;
                }
                if (Utils.isNull(imgUrl)) {
                    MyToast.show("请选择活动封面");
                    return;
                }
                if (contactLittleList.size() == 0) {
                    MyToast.show("请添加活动成员");
                    return;
                }
                if (imgUrl.startsWith("http")) {
                    uploadData();
                } else {
                    uploadPic();
                }

                break;
        }
    }

    int mYear = 0, mMonth = 0, mDay = 0;
    String dayS = "", monthS = "";

    private void showDatePickStartDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mDay == 0) {
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择日期", mYear, mMonth, mDay,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear = year;
                        mMonth = month - 1;
                        mDay = dayOfMonth;
                        if (dayOfMonth > 9) {
                            dayS = dayOfMonth + "";
                        } else {
                            dayS = "0" + dayOfMonth;
                        }
                        if (month > 9) {
                            monthS = month + "";
                        } else {
                            monthS = "0" + month;
                        }
                        if (Utils.getTimeCompareSize(Utils.getCurrentTime2().substring(0, 10), mYear + "-" + monthS + "-" + dayS) == 1) {
                            MyToast.show("开始时间不得早于今天");
                            tvStartTime.setText("");
                            if (!Utils.isNull(tvEndTime.getText().toString())) {
                                if (Utils.getTimeCompareSize(Utils.getCurrentTime2().substring(0, 10), mYear2 + "-" + monthS2 + "-" + dayS2) == 1) {
                                    tvEndTime.setText("");
                                }
                            }
                        } else if (!Utils.isNull(tvEndTime.getText().toString())) {
                            if (Utils.getTimeCompareSize(mYear + "-" + monthS + "-" + dayS,
                                    mYear2 + "-" + monthS2 + "-" + dayS2) == 1) {
                                MyToast.show("开始时间不得晚于结束时间");
                                tvStartTime.setText("");
                            } else {
                                tvStartTime.setText(mYear + "-" + monthS + "-" + dayS);
                            }
                        } else {
                            tvStartTime.setText(mYear + "-" + monthS + "-" + dayS);
                        }
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDay(0);
    }

    int mYear2 = 0, mMonth2 = 0, mDay2 = 0;
    String dayS2 = "", monthS2 = "";

    private void showDatePickEndDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mDay2 == 0) {
            mYear2 = calendar.get(Calendar.YEAR);
            mMonth2 = calendar.get(Calendar.MONTH);
            mDay2 = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择日期", mYear2, mMonth2, mDay2,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear2 = year;
                        mMonth2 = month - 1;
                        mDay2 = dayOfMonth;
                        if (dayOfMonth > 9) {
                            dayS2 = dayOfMonth + "";
                        } else {
                            dayS2 = "0" + dayOfMonth;
                        }
                        if (month > 9) {
                            monthS2 = month + "";
                        } else {
                            monthS2 = "0" + month;
                        }

//                        if (Utils.getTimeCompareSize(Utils.getCurrentTime2().substring(0, 10), mYear2 + "-" + monthS2 + "-" + dayS2) == 1) {
//                            MyToast.show("结束时间不得早于今天");
//                            tvEndTime.setText("");
//                        } else
                        if (!Utils.isNull(tvStartTime.getText().toString())) {
                            if (Utils.getTimeCompareSize(mYear + "-" + monthS + "-" + dayS,
                                    mYear2 + "-" + monthS2 + "-" + dayS2) == 1) {
                                MyToast.show("结束时间不能早于开始时间");
                                tvEndTime.setText("");
                            } else {
                                tvEndTime.setText(mYear2 + "-" + monthS2 + "-" + dayS2);
                            }
                        } else {
                            tvEndTime.setText(mYear2 + "-" + monthS2 + "-" + dayS2);
                        }
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDay(0);
    }
}
